package model

import (
	"errors"
	"haodayizhi/global"

	"gorm.io/gorm"
)

const TableNameRoleRoute = "role_routes"

// RoleRoute mapped from table <role_routes>
type RoleRoute struct {
	RoleID  int64 `gorm:"column:role_id;type:bigint;primaryKey" json:"roleId"`
	RouteID int64 `gorm:"column:route_id;type:bigint;primaryKey" json:"routeId"`
}

// TableName RoleRoute's table name
func (*RoleRoute) TableName() string {
	return TableNameRoleRoute
}

// CreateRoleRoute creates a new RoleRoute in the database.
func (m *RoleRoute) CreateRoleRoute() error {
	if err := global.Db.Create(m).Error; err != nil {
		return err
	}
	return nil
}

// GetRoleRouteByID retrieves a RoleRoute by its ID from the database.
func (m *RoleRoute) GetRoleRouteByID(id int64) (*RoleRoute, error) {
	result := global.Db.First(m, id)
	if result.Error != nil {
		if errors.Is(result.Error, gorm.ErrRecordNotFound) {
			return nil, nil // RoleRoute not found
		}
		return nil, result.Error
	}
	return m, nil
}

// UpdateRoleRoute updates an existing RoleRoute in the database.
func (m *RoleRoute) UpdateRoleRoute() error {
	if err := global.Db.Save(m).Error; err != nil {
		return err
	}
	return nil
}

// DeleteRoleRoute deletes a RoleRoute by its ID from the database.
func (m *RoleRoute) DeleteRoleRoute(id int64) error {
	if err := global.Db.Delete(m, id).Error; err != nil {
		return err
	}
	return nil
}

// 查询出所有的角色路由，传入角色ID，查询出该角色的路由id 过滤其他字段
func (m *RoleRoute) GetRoutesByRoleID(roleId int64) ([]*RoleRoute, error) {
	var routes []*RoleRoute
	result := global.Db.Where("role_id = ?", roleId).Find(&routes)
	if result.Error != nil {
		return nil, result.Error
	}
	return routes, nil
}
